Spring boot 整合PowerMock

依赖

1
2
3
4
5
6
7
8
9
10
11
12
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-module-junit4</artifactId>
<version>2.0.0-beta5</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-api-mockito2</artifactId>
<version>2.0.0-beta5</version>
<scope>test</scope>
</dependency>

整合

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
@PrepareForTest({HiveAccessConfigDao.class, DataIntegrationConfigDao.class})
@SpringBootTest
@RunWith(SpringRunner.class)
public class HiveAccessConfigServiceImplTest {
@Mock
private HiveAccessConfigDao hiveAccessConfigDao;
@Autowired
@InjectMocks
private HiveAccessConfigServiceImpl hiveAccessConfigService;

@Before
public void init() {
MockitoAnnotations.initMocks(this);
}

@Test
public void queryById() {
HiveAccessConfig hiveAccessConfig = new HiveAccessConfig();
hiveAccessConfig.setId(2);
PowerMockito.when(hiveAccessConfigDao.selectByPrimaryKey(Mockito.anyInt())).thenReturn(hiveAccessConfig);
assertEquals(hiveAccessConfigService.queryById(2).getId(), hiveAccessConfig.getId());
}
}

注意: 这里@RunWith注解没有使用 PowerMockRunner 为的是使用spring 容器的自动注入功能,这样我们只需要mock 需要mock的service或者dao层,其他的使用spring 容器中的bean。

由于没有使用 PowerMockRunner 加载,所以需要使用MockitoAnnotations.initMocks(this); 方法来初始化这个测试类,动态代理需要mock的bean(PowerMock普通方法是基于Mockito通过动态代理实现的,而静态方法,finnal,private方法等mock则是通过修改字节码)。否则上面注入到hiveAccessConfigService 的hiveAccessConfigDao则还是spring中的bean,达不到mock的目的。